package exercise;

/*
b.建立exception包，建立Bank类，
类中有变量double balance表示存款,
Bank类的构造方法能增加存款，

Bank类中有取款的发方法withDrawal(double dAmount),
当取款的数额大于存款时,抛出BalanceException
取款数额为负数，抛出NagativeException,
如new Bank(100),表示存入银行100元，当用方法withdrawal(150)，withdrawal(-15)时会抛出自定义异常。

BalanceException    自定义异常   表示余额不足
NegativeException        自定义异常   表示取款数不能为负数
 */
public class ex02 {
    public static void main(String[] args) {
        Bank bank = new Bank(100);
        bank.withdraw(-1);
        System.out.println("当前余额为：" + bank.getBalance());

    }
}

class Bank {
    private double balance;

    public double getBalance() {
        return balance;
    }

    public Bank(double balance) {
        this.balance = balance;
    }

    public void withdraw(double dAmount) {
        if (dAmount > balance) {
            try {
                throw new BalanceException("余额不足，全部取出");
            } catch (BalanceException e) {
                System.err.println(e.getMessage());
                dAmount = balance;
            }
        }
        if (dAmount < 0) {
            try {
                throw new NegativeException("取款数不能为负数");
            } catch (NegativeException e) {
                System.err.println(e.getMessage());
                dAmount = 0;
            }
        }
        this.balance -= dAmount;
    }
}

// 自定义异常   表示余额不足
class BalanceException extends Exception {
    public BalanceException(String message) {
        super(message);
    }
}

//自定义异常   表示取款数不能为负数
class NegativeException extends RuntimeException {
    public NegativeException(String message) {
        super(message);
    }
}